<template>
  <base-modal
    :show.sync="show"
    width="990px"
    class="creat-card-dialog"
    @closed="onClose"
  >
    <div slot="title">
      <span class="el-dialog__title">{{$t('task.setting.taskTypeSetting.flow.components.addComponent')}}</span>
    </div>
    <div class="base-modal-content">
      <div class="base-card-heard">
        <div class="base-card-msg"><i class="el-icon-warning"></i> <span> {{$t('task.setting.taskTypeSetting.flow.components.taskCardTitle1')}}</span></div>
        <div class="radio-type">
          <div>
            <el-radio v-model="selectRadio" label="exist">{{$t('task.setting.taskTypeSetting.flow.components.taskCardTitle2')}}</el-radio>
            <el-radio v-model="selectRadio" label="stock">{{$t('task.setting.taskTypeSetting.flow.components.taskCardTitle3')}}</el-radio>
          </div>
          <el-button v-if="selectRadio === 'exist'" type="primary" @click="addTaskCard">{{$t('common.base.add')}}</el-button>
        </div>

      </div>
      <!-- start 从已添加的组件库选择 -->
      <el-table
        v-if="selectRadio == 'exist'"
        ref="multipleTable"
        :data="tableCardData"
        style="width: 100%"
        class="page-table"
        :highlight-current-row="false"
        header-row-class-name="page-table-header"
        stripe
        tooltip-effect="dark"
      >
        <el-table-column type="index" :label="$t('common.base.SN')" width="60px"></el-table-column>
        <el-table-column prop="name" :label="$t('common.base.name')" show-overflow-tooltip>
          <template slot-scope="scope">
            <pre class="pre-text">{{ getCardNameLabel(scope.row) }}</pre>
          </template>
        </el-table-column>
        <el-table-column prop="description" :label="$t('common.form.type.description')" show-overflow-tooltip>
          <template slot-scope="scope">
            <pre class="pre-text">{{ htmlUnEscape(scope.row.description) }}</pre>
          </template>
        </el-table-column> 
        <el-table-column prop="inputType" :label="$t('task.setting.taskTypeSetting.flow.components.taskCardTitle4')" width="160px">
          <template slot-scope="scope">{{ scope.row.inputType == 'single' ? $t('common.base.onceTime') : $t('common.base.moreTime') }}</template>
        </el-table-column>
        <el-table-column prop="enabled" :label="$t('common.base.status')" width="100px">
          <template slot-scope="scope">{{ scope.row.enabled == 1 ? $t('common.base.enable') : $t('common.base.disable') }}</template>
        </el-table-column>
        <el-table-column prop="checked" :label="$t('common.base.enable')" width="100px">
          <template slot-scope="scope">
            <el-checkbox :disabled="!scope.row.enabled" v-model="scope.row.checked"></el-checkbox>
          </template>
        </el-table-column>
      </el-table>
      <!-- end 从已添加的组件库选择 -->

      <!-- start从模版库中选择-->
      <div v-if="selectRadio == 'stock'">
        <template-library @saveImport="saveImport" :card-group="cardGroup"></template-library>
      </div>
      <!-- start 从模版库中选择-->
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onSubmit">{{$t('common.base.makeSure')}}</el-button>
    </div>

    <!-- 创建附加组件 -->
    <edit-cardname-dialog ref="batchCardnameDialog" from="CreatCardDialog" @onSuccess="onSuccessCardname"></edit-cardname-dialog>
  </base-modal>
</template>
<script>
// api
import * as SettingTaskApi from '@src/api/SettingTaskApi';
import { uniqBy, cloneDeep } from 'lodash';
// util
import { isShowCardWorkTime, isStandardEdition, isExperienceEdition, isBasicEditionHideSystemCard } from '@shb-lib/version'
// components
import templateLibrary from './templateLibrary';
import { CardNameLabelEnum } from '@model/enum/LabelEnum'
import EditCardnameDialog from '@src/modules/setting/task/taskAdditionalSetting/manage/components/EditCardnameDialog.vue';
/* mixin */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'

export default {
  name: 'creat-card-dialog',
  mixins: [VersionControlTaskMixin],
  props: {
    taskCardList: {
      type: Array,
      default: () => [],
    },
    taskTypeId: {
      type: String,
    },
    visiable: {
      type: Boolean,
    },
  },
  data() {
    return {
      cardGroup: {},
      cardSysList:[],
      selectRadio:'exist',
      tableCardData:[],
      roleList:[],
      show: false, 
    };
  },
  computed: {
    isShowCardWorkTime() {
      return this._isShowCardWorkTime
    },
    isBasicEditionHideSystemCard() {
      return isBasicEditionHideSystemCard() 
    },
  },
  watch: {
    visiable(newValue) {
      this.show = newValue;
      if (newValue) {
        this.selectRadio = 'exist';
        this.getEnabledListReq();
        this.initCardSysList();  
      }
    },
  },
  methods: {
    // 获取附加组件标题的多语言label
    getCardNameLabel(item) {
      const { name, cardNameLanguage } = item
      const locale = this.$i18n.locale
      return cardNameLanguage?.locale || CardNameLabelEnum[name] || name
    },
    saveImport(cardSelected){
      this.$emit('updateImport', cardSelected)
    },
    onClose() {
      this.$emit('onClose');
    },
    onSubmit() {
      if(this.selectRadio == 'exist'){
        // 新增组件
        this.saveCardChecked();
      }else{
        // 关闭
        this.onClose();
      }
     
    },
    // 获取已添加的组件库列表
    getEnabledListReq() {
      SettingTaskApi.getAllCardList()
        .then((res) => {
          const { code, message, result = [] } = res
          if (code != 0) {
            return this.$message.error(message)
          }
          
          let cardList = result.slice()
          
          // 标准基础版和体验版 过滤工时记录组件
          if (!this.isShowCardWorkTime) {
            cardList = cardList.filter(card => card?.specialfrom !== '工时记录')
          }

          // 基础版过滤工时记录、备件清单、服务清单模块
          if (this.isBasicEditionHideSystemCard) {
            cardList = cardList.filter(card => card?.specialfrom !== '工时记录' && card.specialfrom !== '备件清单' && card.specialfrom !== '服务清单')
          }
          
          this.mergeSelect(cardList)
          
        })
        .catch((error) => {
          console.error(error)
        });
    },

    /** 
    * @description 已存在组件选中
    * 存在相同数据 则checked为true 不同则checked为false
    */
    mergeSelect(cardLists) {
      for(let i = 0;i < cardLists.length; i++){
        let card = cardLists[i];

        let index = -1;
        for(let j = 0; j < this.taskCardList.length; j++){
          if(card.id == this.taskCardList[j].id){
            index = j;
            card.checked = true;
            break;
          }
        }
        if(index < 0){
          card.checked = false;
        }
      }
      this.tableCardData = cardLists;
      
    },
    // 创建附加组件
    saveCardChecked() {
      let cardChecked = [];
      this.tableCardData.forEach(item=>{
        let cardSelected = {};
        if(item.checked){
          cardSelected.id = item.id;
          cardSelected.inputType = item.inputType;
          cardSelected.name = item.name;
          cardSelected.enabled = item.enabled;
          cardSelected.specialfrom = item.specialfrom ? item.specialfrom : '';
          cardChecked.push(cardSelected)
        }
      });

      // 不允许同时选择备件和物料
      let cardName = ['备件清单', '物料申领'] 
      let haveCardName = cardChecked.length > 0 && cardName.every(item => cardChecked.findIndex(card => card.name === item) > -1)
      if(haveCardName) return this.$message.warning(this.$t('task.setting.taskTypeSetting.flow.components.taskCardTip1'))

      this.$emit('update', cardChecked)
    },

    // 修改附加组件
    onUpdateCardReq() {
      const params = {
        description: this.form.description,
        id: this.form.id,
        name: this.form.name,
      };
      SettingTaskApi.onUpdateCard(params)
        .then((res) => {
          const { status, message, data } = res;
          if (status == 0) {
            this.$message.success(this.$t('common.base.tip.editSuccess'));
            location.reload();
          } else {
            this.$message.error(message);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    // 获取附加组件的信息
    getCardInfoReq() {
      SettingTaskApi.getCardInfo({ id: this.form.id })
        .then((res) => {
          const { status, message, data } = res;
          if (status == 0) {
            this.form = data;
          }
        })
        .catch((error) => ({}));
    },
    /** 
    * @description 获取组件库列表
    * 1.工时记录灰度控制 isShowCardWorkTime true显示 false隐藏
    */
    initCardSysList() {
      SettingTaskApi.getCardSysList().then(res=>{
        const { code, message, result } = res;
        if(code == 0){
          let cardList = result || [];
          
          if(!this.isShowCardWorkTime) {
            cardList = cardList.filter(function(card) {
              return card.cardName !== '工时记录';
            })
          }

          // 基础版过滤工时记录、备件清单、服务清单模块
          if (this.isBasicEditionHideSystemCard) {
            cardList = cardList.filter(card => card.cardName !== '工时记录' && card.cardName !== '备件清单' && card.cardName !== '服务清单')
          }
          
          let cardAll = cardList.slice();
          this.cardGroup = this.groupBy(cardAll, 'type')
        }else{
          this.$message.error(message);
        }
      }).catch(error=>{
        console.log(error)
      })
    },
    groupBy(cardAll, type) { 
      let cardObj = cardAll.reduce(
        (acc, card) => {
          if (!acc[card[type]]) {
            acc[card[type]] = []
          }
          acc[card[type]].push(card)
          return acc
        }, {})
      return cardObj
    },
    htmlUnEscape(value){
      if(!value) return '';
      return value.replace( /&lt;/g, '<').replace(/&gt;/g, '>');
    },
    // 新建组件
    addTaskCard(){
      this.$refs.batchCardnameDialog.openDialog();
    },
    // 刷新列表
    onSuccessCardname() {
      this.getEnabledListReq();
    }
  },
  components: {
    [templateLibrary.name]: templateLibrary,   
    [EditCardnameDialog.name]: EditCardnameDialog
  },
};
</script>
<style lang="scss">
.creat-card-dialog {
  .base-modal-header {
    display: flex;
    justify-content: space-between;
    .el-dialog__title {
      font-size: 18px;
    }
    .el-tooltip {
      color: #999;
    }
  }
  .base-modal-body {
    padding: 20px;
  }
  .base-modal-content {
    .base-card-heard{
      width: 900px;
      .base-card-msg{
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);
        background: #E6F7FF;
        border-radius: 2px;
        border: 1px solid #91D5FF;
        margin-bottom: 12px;
        .el-icon-warning{
          color: $color-primary;
          margin-left: 17px;
        }
      }
      .radio-type{
        margin-bottom: 9px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
    .page-table{
      padding: 0;
    }
  }
}
</style>
